import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import img1 from '@/assets/imgs/login/user_avatar.png'
export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const isLoggedIn = computed(() => !!user.value)
  const isAuthenticated = computed(() => !!user.value) // Alias for consistency
  const username = computed(() => user.value?.username)

  // 模拟用户数据
  const mockUser = {
    username: 'admin',
    avatar: img1,
    token: 'mock-jwt-token',
  }

  function login(username, password) {
    return new Promise((resolve, reject) => {
      // 模拟API请求延迟
      setTimeout(() => {
        if (username === 'admin' && password === 'admin') {
          user.value = mockUser
          localStorage.setItem('user', JSON.stringify(mockUser))
          resolve(mockUser)
        } else {
          reject(new Error('用户名或密码错误'))
        }
      }, 800)
    })
  }

  function logout() {
    user.value = null
    localStorage.removeItem('user')
  }

  // 初始化时从localStorage加载用户信息
  function initialize() {
    const savedUser = localStorage.getItem('user')
    if (savedUser) {
      user.value = JSON.parse(savedUser)
    }
  }

  return {
    user,
    isLoggedIn,
    isAuthenticated, // Add this to exports
    username,
    login,
    logout,
    initialize,
  }
})
